package io.demo.message.serial;

import com.google.protobuf.Message;
import io.demo.message.domain.proto.MessageConverters;

public class ProtobufSerializedObject<T> extends SerializedObject<T> {

  ProtobufSerializedObject(T object) {
    super(object);
  }

  @Override
  protected void beforeSerialize() {
    // nothing to do.
  }

  @Override
  protected byte[] doSerialization(T object) {
    @SuppressWarnings("unchecked")
    Class<T> objectClass = (Class<T>) object.getClass();
    Message message = MessageConverters.toMessage(object, objectClass);
    return message.toByteArray();
  }

  @Override
  public T reverse() {
    Message message = MessageConverters.parseFrom(getByteArray(), getObjectClass());
    @SuppressWarnings("unchecked")
    T originCopy = (T) MessageConverters.fromMessage(message, getObjectClass());
    return originCopy;
  }
}
